﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ShopOnline.Models.Utils
{
    public  partial class ShoppingCart
    {
        ShopOnlineDBDataContext storeDB = new ShopOnlineDBDataContext();
        string shoppingCartId { get; set; }
        public const string CartSessionKey = "CartId";

        public static ShoppingCart getCart(HttpContextBase context)
        {
            ShoppingCart cart = new ShoppingCart();
            cart.shoppingCartId =cart.GetCartId(context);
            return cart;

        }

        public void AddtoCart(Product product)
        {
            Cart cartItem = storeDB.Carts.SingleOrDefault(c => c.cartId == shoppingCartId && c.productId == product.productId);
            if (cartItem == null)
            {
                cartItem = new Cart();
                cartItem.productId = product.productId;
                cartItem.cartId = shoppingCartId;
                cartItem.dateCreate = DateTime.Now;
                cartItem.count = 1;
            }
            else
            {
                cartItem.count++;
            }
            storeDB.Carts_update(cartItem.recordId, cartItem.cartId, cartItem.productId, cartItem.count, cartItem.dateCreate);
        }

        public void RemovefromCart(int id)
        {
            var cartItem = storeDB.Carts.SingleOrDefault(c => c.recordId == id && c.cartId == shoppingCartId);
            if (cartItem != null)
            {
                if (cartItem.count > 0)
                {
                    cartItem.count--;
                    storeDB.Carts_update(cartItem.recordId, cartItem.cartId, cartItem.productId, cartItem.count, cartItem.dateCreate);
                }
                else
                {
                    storeDB.Carts_delete(id);
                }
            }         
        }

        public void EmptyCart()
        {
            var list = (from c in storeDB.Carts where c.cartId == shoppingCartId select c).ToList();
                foreach (var cart in list)
                {
                    storeDB.Carts_delete(cart.recordId);
                }
        }
        public List<Cart> GetCartItems()
        {
            var cartItems = (from cart in storeDB.Carts
                             where cart.cartId == shoppingCartId
                             select cart).ToList();
            return cartItems;
        }

        public int GetCount()
        {
            int? count = (from cartItems in storeDB.Carts
                          where cartItems.cartId == shoppingCartId
                          select (int?)cartItems.count).Sum();

            return count ?? 0;
        }

        public decimal GetTotal()
        {
            decimal? total =
                (from cartItems in storeDB.Carts
                 where cartItems.cartId == shoppingCartId
                 select (int?)cartItems.count * cartItems.Product.unitPrice)
                .Sum();

            return total ?? decimal.Zero;
        }

        public int CreateOrder(Order order)
        {
            decimal orderTotal = 0;

            var cartItems = GetCartItems();

            //Iterate the items in the cart, adding Order Details for each
            foreach (var cartItem in cartItems)
            {
                var orderDetails = new OrderDetail();
                
                    orderDetails.productId = cartItem.productId;
                    orderDetails.orderId = order.orderId;
                    orderDetails.unitPrice = cartItem.Product.unitPrice;
                    orderDetails.quantity = cartItem.count;
                    storeDB.OrderDetails.InsertOnSubmit(orderDetails);
                    storeDB.SubmitChanges();
                orderTotal += (cartItem.count * cartItem.Product.unitPrice);
            }

            //Save the order
            
            //Empty the shopping cart
            EmptyCart();

            //Return the OrderId as a confirmation number
            return order.orderId;
        }

        public String GetCartId(HttpContextBase context)
        {
            if (context.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrEmpty(context.User.Identity.Name))
                {
                    // User is logged in, associate the cart with there username
                    context.Session[CartSessionKey] = context.User.Identity.Name;
                }
                else
                {
                    // Generate a new random GUID using System.Guid Class
                    Guid tempCartId = Guid.NewGuid();

                    // Send tempCartId back to client as a cookie
                    context.Session[CartSessionKey] = tempCartId.ToString();
                }
            }
            return context.Session[CartSessionKey].ToString();
        }

        public void MigrateCart(string userName)
        {
            var shoppingCart = storeDB.Carts
                .Where(c => c.cartId == shoppingCartId);

            foreach (Cart item in shoppingCart)
            {
                item.cartId = userName;
                storeDB.Carts_update(item.recordId, item.cartId, item.productId, item.count, item.dateCreate);
            }   
        }
    }
}